<?php 

include 'Channel.php';

session_start();

$channel_num = $_GET['channel'];

//Open connection
$conn = mysql_connect("localhost", "root", "a65d68r");
mysql_select_db("cis", $conn);

//Check if the current user can access the desired channel
if(!isset($_SESSION['channels']) || $channel_num != $_SESSION['channels']) {
	echo "{error: \"Permission denied\", debug:".json_encode($_SESSION['channels'])."}";
	return;
}

if(!isset($_SESSION['timestamp'])) {
	$_SESSION['timestamp'] = microtime(true)*1000;
}

$channel = Channel::getInstance($channel_num);

$channel->setOptions(array("db_connection" => $conn));

$message = $channel->getMessage(0);

if(!empty($message)) {
	$_SESSION['timestamp'] = $message[count($message)-1]['timestamp'];
}

echo json_encode($message);

?>